#encoding=utf8
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import *
from django.shortcuts import *
from utils.decorators import *
from trp.models import *
from django.http.response import HttpResponse
from utils.JsonResponse import *
from utils.report import *
from django.db.models.query_utils import Q
import json
from django.db.models import Sum
from utils.utils import *
from trp.views.costlog import get_cost_by_strategy
from django.db import transaction
from django.template.defaultfilters import floatformat
from utils.utils import date_range_array
from decimal import Decimal
@login_required
def main(request):
    account = request.user.account
    if account.is_platform_user():
        return strategy_response(request,'trp/strategy_platform.html',{})
    elif account.is_vendor_user() or account.is_merchant_user():
        return strategy_response(request,'trp/strategy_merchant.html',{})
    
def strategy_response(request,html,dic):
    return render_to_response(html, dict({'user' : request.user, 'page' : 'strategy'},**dic))   

@login_required_ajax
def get_list(request):
    params = json.loads(request.body)
    traffic_id=params.get("traffic_id")
    resource_id=params.get("resource")
    
    account = request.user.account
    search_text = params.get("search_text", "")  # 模糊搜索
    start = params.get("start")
    end = params.get("end")
    order_by = params.get("orderBy", "-id")
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))
    state=-1
    if params.get("state"):
        state=int(params.get("state"))
    
    org=account.get_organization()    
    
    args = []  
    kwargs = {}  
    order = []  
    if start:
        args.append(Q(start__range=(start,end)) | Q(end__range=(start,end))|Q(start__lte=start,end__gte=end)|Q(start__gte=start,end__lte=end))
    kwargs['priority__gte']=0
    kwargs['deleted'] = False
    kwargs['organization']=org
    
    if search_text:
        args.append(Q(name__icontains=search_text));
    if order_by:
        order.append(order_by)
    if traffic_id:
        traffic=Traffic.objects.get(pk=traffic_id)
        resource=traffic.TRAFFIC.all()
        sids=ResourcePrice.objects.filter(resource__in=resource).values_list("strategy_id",flat=True)       
        kwargs['id__in']=sids    
    if resource_id:
        resource=Resource.objects.get(pk=resource_id)
        sids=ResourcePrice.objects.filter(resource=resource).values_list("strategy_id",flat=True)       
        kwargs['id__in']=sids 
    now=datetime.datetime.now()
    now=datetime.datetime(now.year,now.month,now.day)    
    if state==0:
        kwargs['start__gt']=now
    elif state==1:
        kwargs['start__lte']=now
        kwargs['end__gte']=now
    elif state==2:    
        kwargs['end__lt']=now
    list = Strategy.objects.filter(*args, **kwargs).order_by(*order).distinct()
    paginator = Paginator(list, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)    
    results = {}
    datalist = strategy_to_json(pageObj.object_list,state)    
    results['bodyData'] = datalist   
    results["pageNo"] = pageNo
    results["pageSize"] = pageSize
    results["totalCount"] = paginator.count    
    return JsonResponse(results)    

@login_required_ajax
@transaction.commit_manually
def create_or_update(request):
    data=json.loads(request.body)
    org=request.user.account.get_organization()
    id=-1
    operation_log=OperationLog()
    if data.get("id"):
        id=int(data["id"])
        operation_log.operation="修改"
        details="修改成功,"
    else:
        operation_log.operation="新建"
        details="新建成功,"
    name=data["name"]   
    consume_type_in=int(data.get("consume_type_in",0))    
    consume_type_out=int(data.get("consume_type_out",0)) 
    consume_type_ally=int(data.get("consume_type_ally",0)) 
    price=0;
    total_amount_in=0
    total_amount_out=0
    total_amount_ally=0
    daily_amount_in=0
    daily_amount_out=0
    daily_amount_ally=0
    total_budget_in=0
    total_budget_out=0
    total_budget_ally=0
    daily_budget_in=0
    daily_budget_out=0
    daily_budget_ally=0
    frequency=0

    if data.get("price"):
        price=float(data.get("price"))
    if data.get("frequency"):
        frequency=int(data.get("frequency"))
    if data.get("totalAmountIn"):
        total_amount_in=float(data.get("totalAmountIn"))
    if data.get("totalAmountOut"):
        total_amount_out=float(data.get("totalAmountOut"))
    if data.get("totalAmountAlly"):
        total_amount_ally=float(data.get("totalAmountAlly"))
    if data.get("dailyAmountIn"):
        daily_amount_in=float(data.get("dailyAmountIn"))
    if data.get("dailyAmountOut"):
        daily_amount_out=float(data.get("dailyAmountOut"))
    if data.get("dailyAmountAlly"):
        daily_amount_ally=float(data.get("dailyAmountAlly"))
    if data.get("totalBudgetIn"):
        total_budget_in=float(data.get("totalBudgetIn"))
    if data.get("totalBudgetOut"):
        total_budget_out=float(data.get("totalBudgetOut"))
    if data.get("totalBudgetAlly"):
        total_budget_ally=float(data.get("totalBudgetAlly"))
    if data.get("dailyBudgetIn"):
        daily_budget_in=float(data.get("dailyBudgetIn"))
    if data.get("dailyBudgetOut"):
        daily_budget_out=float(data.get("dailyBudgetOut"))
    if data.get("dailyBudgetAlly"):
        daily_budget_ally=float(data.get("dailyBudgetAlly"))
    
    landingPage=data.get("landingPage","")
    start=data["start"]
    end=data["end"]
    hours=data["hours"]
    areas=data["areas"]
    materials=data["materials"]
    words=data["words"]
    
    resources=build_resources_price(data["resource"],price,org.type)
    
     
    if org.type==0:
        priority=10   
    else:
        priority=20
    
    try:
        if id>0:
            obj=Strategy.objects.get(pk=id)
            obj.name=name
        else:
            obj=Strategy(name=name)
        obj.start=start
        obj.end=end
        obj.total_amount_in=total_amount_in
        obj.total_amount_out=total_amount_out
        obj.total_amount_ally=total_amount_ally
        obj.daily_amount_in=daily_amount_in
        obj.daily_amount_out=daily_amount_out
        obj.daily_amount_ally=daily_amount_ally
        obj.total_budget_in=total_budget_in
        obj.total_budget_out=total_budget_out
        obj.total_budget_ally=total_budget_ally
        obj.daily_budget_in=daily_budget_in
        obj.daily_budget_out=daily_budget_out
        obj.daily_budget_ally=daily_budget_ally
        obj.landingpage=landingPage
        obj.consume_type_in=consume_type_in
        obj.consume_type_out=consume_type_out
        obj.consume_type_ally=consume_type_ally
        obj.frequency=frequency
        obj.priority=priority
        obj.organization=org
        alg=data.get("algorithm")
        if alg!=None and alg!="":
            obj.algorithm_id=int(alg)
            parameters=data.get("parameters","")
            obj.parameters=parameters
        else:
            obj.algorithm=None
            obj.parameters=""
            
        obj.save()
        obj.set_resource_prices(resources)
        obj.set_material_weights(materials)
        obj.set_areas(areas)
        obj.set_hours(hours)
        obj.set_words(words)
        id=obj.id
        operation_log.object="策略"
        operation_log.user=request.user
        operation_log.object_id=id
        operation_log.details=details+"策略id="+str(id)
        operation_log.save()
        result={}
    except:
        transaction.rollback()
        return JsonResponseBadrequest({})
    else:
        transaction.commit()
    return JsonResponse(result)      

@login_required_ajax
@transaction.commit_manually
def delete(request):
    if request.method == "POST":
        params = request.POST
    else:
        params = request.GET
    try:
        id=int(params.get("id"))
        obj=Strategy.objects.get(pk=id)
        start=obj.start
        now = datetime.datetime.now().date()
        if start > now :
            obj.deleted=True
            obj.save()
            ResourcePrice.objects.filter(strategy_id=id).delete()
            operation_log=OperationLog()
            operation_log.operation="删除"
            operation_log.object="策略"
            operation_log.user=request.user
            operation_log.object_id=id
            operation_log.details="删除策略成功,策略id="+str(id)
            operation_log.save()
    except:
        transaction.rollback()
        return JsonResponseBadrequest({})
    else:
        transaction.commit()
    return JsonResponse({})
 
@login_required_ajax
def report(request):
    results={}
    account = request.user.account
    if account.is_platform_user():
        role=1
    elif account.is_vendor_user() or account.is_merchant_user():
        role=2
    else:
        return JsonResponse(results)     
    if request.method == "POST":
        params = request.POST
    else:
        params = request.GET
    
    sid=int(params.get("strategy_id"))
    pid=int(params.get("position_id",-1))   
    type=params.get("type")
    start = params.get("start")
    end = params.get("end")
    
           
    chart_report=get_strategy_dailyreport(pid,type,role,sid,start,end)   
    #today_report=get_strategy_todayreport(id)
    results["data"]=chart_report
    #results["today_data"]=today_report
    results["positions"]=get_position(sid)    
    return JsonResponse(results)

# def get_material(request):
#     results={}
#     data=json.loads(request.body)
#     ids=data["traffic_ids"]
#     sid={}
#     if data.get("strategy_id"):
#         sid=data["strategy_id"]       
#     if ids:
#         datalist=get_material_list(ids,sid)
#         results["data"]=datalist
#     return JsonResponse(results) 

@login_required_ajax
def get_material(request):
    result={}
    params=json.loads(request.body)   
    org=request.user.account.get_organization()
    sid=params.get("strategy_id")       
    groupTag=params.get("group",0)        
    tid=params.get("traffic_id")
    resource_ids=params.get("resource_ids")
    group={}
    groupIds=[]
    if result.get("group")==None:
        result["group"]=[]
    if groupTag >0:
        if tid:
            tid=int(tid)
            resource=Resource.objects.get(traffic_id=tid,is_default=True)
            resource_ids=[]
            resource_ids.append(resource.id)
            params["resource_ids"]=resource_ids
            strategy=get_default_traffic_strategy({"tid":tid})
        else:
            if sid:
                sid =int(sid)
                strategy=Strategy.objects.get(pk=sid)
            else:
                resource_id=resource_ids[0]
                strategy=get_default_resource_strategy(resource_id)
        mws=strategy.materialweight_set.all()
        groupWeights=mws.values('group').annotate(weight=Sum('weight'))
        for gw in groupWeights:
            groupName=gw["group"]
            weight=float(gw["weight"])
            if group.get(groupName)==None:
                group[groupName]={}
                if group[groupName].get("materials")==None:
                    group[groupName]["materials"]=[]
                    group[groupName]["weight"]=round(weight/100)
                    group[groupName]["name"]=groupName
        if mws.count()>0:
            for mw in mws:
                m=mw.material
                data={}
                data["id"]=m.id
                data["name"]=m.name
                data["width"]=m.width
                data["height"]=m.height
                data["status"]=m.status
                data["landingpage"]=m.landingpage
                data["type"]=m.type and m.type.name
                data["tags"]=get_tag_name(m.tags.all())
                groupName=unicode(mw.group)               
                group[groupName]["materials"].append(data)
#                 groupIds.append(m.id)                
            for (k,v) in  group.items(): 
                result["group"].append(v)       
    
    results=get_materialData_By_Traffic(groupIds,params,org)      
    result["bodyData"]=results["bodyData"] 
    result["sizedata"]=results["sizedata"]
    result["pageNo"] = results["pageNo"]
    result["pageSize"] = results["pageSize"]
    result["totalCount"] = results["totalCount"]         
        
    return JsonResponse(result) 


def get_group_material(sid,org):   
    mws=Strategy.objects.get(pk=sid).materialweight_set.all()                   
    groupWeights=mws.values('group').annotate(weight=Sum('weight'))
    group={}
    datalist=[]
    for gw in groupWeights:
        groupName=gw["group"]
        weight=float(gw["weight"])
        if group.get(groupName)==None:
            group[groupName]={}
            if group[groupName].get("materials")==None:
                group[groupName]["materials"]=[]
                group[groupName]["weight"]=round(weight/100)
                group[groupName]["name"]=groupName
    if mws.count()>0:
        for mw in mws:
            m=mw.material
            data={}
            data["id"]=m.id
            data["name"]=m.name
            data["width"]=m.width
            data["height"]=m.height
            data["status"]=m.status
            data["landingpage"]=m.landingpage
            data["tags"]=get_tag_name(m.tags.all())
            groupName=unicode(mw.group)
            group[groupName]["materials"].append(data)                           
        for (k,v) in  group.items(): 
                datalist.append(v)           
    return datalist
 

def get_materialData_By_Traffic(groupIds,params,org):
    search_text = params.get("search_text", "")    
    pageSize = int(params.get("pageSize", 20))
    pageNo = int(params.get("pageNo", 1))
    state=int(params.get("status",-1))
    width=params.get("width")
    height=params.get("height")
    sizeTag=params.get("sizeTag")
    type=params.get("type")
    ids=params["resource_ids"]
    datalist=[]
    args=[]    
    kwargs = {}
    sizedata={}
    sizelist=[]
    args.append(Q(organization=org))
    if search_text:
        args.append(Q(name__icontains=search_text)| Q(tags__name__icontains=search_text));
    if width:
        args.append(Q(width=width))
        args.append(Q(height=height))    
    if type!=None and type!="":
        args.append(Q(type_id=int(type)))
    condi=Q(id=-1)
    for id in ids:
        traffic = Resource.objects.get(pk=int(id)).traffic
        position=traffic.position
        width=position.width
        height=position.height
        max=float(position.max)
        if position.show_type==2:
            if position.arrange_type==0:
                width=width/max
            else:
                height=height/max           
        size=position.size
        types=position.types.values_list("id",flat=True)        
        condi=condi|Q(width=width,height=height,size__lte=size,type_id__in=types)      
    args.append(Q(status=1))
    list=Material.objects.prefetch_related("type").select_related().filter(condi,*args).exclude(id__in=groupIds)  
    paginator = Paginator(list, pageSize)
    try:
        size_tuple=list.values_list("width","height").distinct()
        for size_obj in size_tuple:
            tmp={}
            tmp["width"]=size_obj[0]
            tmp["height"]=size_obj[1]
            sizelist.append(tmp)
        objs = paginator.page(pageNo)
        for obj in objs:
            data={}
            data["id"]=obj.id
            data["name"]=obj.name
            data["width"]=obj.width
            data["height"]=obj.height
            data["status"]=obj.status
            data["landingpage"]=obj.landingpage
            data["tags"]=get_tag_name(obj.tags.all())
            data["type"]=obj.type and obj.type.name
            datalist.append(data)            
#             str='%s * %s' %(obj.width,obj.height)
#             if sizeTag and sizedata.get(str)==None:
#                 tmp = {}
#                 tmp["width"]=obj.width
#                 tmp["height"]=obj.height
#                 sizelist.append(tmp)
#                 sizedata[str]=str
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)    
    results = {}      
    results['bodyData'] = datalist   
    results["pageNo"] = pageNo
    results["pageSize"] = pageSize
    results["totalCount"] = paginator.count    
    results["sizedata"]=sizelist
    return results    
       
   

#data={"ungroup":[material],"group":[{"name":"group1","weight":12,"materials:[material]}]}
#{u'group1': {'data': [{'tags': [u'material tag 3', u'material tag 13', u'material tag 20'], 'id': 1L, 'name': u'platform material 1'}], 'name': u'group1', 'weight': 100}}

def get_material_list(ids,sid):
    result={}
    group={}
    groupData=[]
    groupIds=[]
    if result.get("group")==None:
        result["group"]=[]
    if sid:
        mws=Strategy.objects.get(pk=sid).materialweight_set.all()
        groupWeights=mws.values('group').annotate(weight=Sum('weight'))
        for gw in groupWeights:
            groupName=gw["group"]
            weight=gw["weight"]
            if group.get(groupName)==None:
                group[groupName]={}
                if group[groupName].get("materials")==None:
                    group[groupName]["materials"]=[]
                    group[groupName]["weight"]=weight
                    group[groupName]["name"]=groupName
        if mws.count()>0:
            for mw in mws:
                m=mw.material
                data={}
                data["id"]=m.id
                data["name"]=m.name
                data["width"]=m.width
                data["height"]=m.height
                data["status"]=m.status
                data["landingpage"]=m.landingpage
                data["tags"]=get_tag_name(m.tags.all())
                groupName=unicode(mw.group)               
                group[groupName]["materials"].append(data)
                groupIds.append(m.id)                
            for (k,v) in  group.items(): 
                result["group"].append(v)           
    result["ungroup"]=get_materialData_By_Traffic(ids,groupIds)        
    return result 

# def get_materialData_By_Traffic(ids,groupIds):
#     datas=[]
#     for id in ids:
#         position=Traffic.objects.get(pk=id).position
#         width=position.width
#         height=position.height
#         size=position.size
#         objs=Material.objects.filter(width=width,height=height,size__lte=size,~Q(status=2)).exclude(id__in=groupIds)
#         for obj in objs:
#             data={}
#             data["id"]=obj.id
#             data["name"]=obj.name
#             data["width"]=obj.width
#             data["height"]=obj.height
#             data["status"]=obj.status
#             data["landingpage"]=obj.landingpage
#             data["tags"]=get_tag_name(obj.tags.all())
#             datas.append(data)
#             groupIds.append(obj.id)
#     return datas
    
def get_tag_name(objs):
    data=[]
    for obj in objs:
        data.append(obj.name)
    return data  

def create_default_strategy(traffic_id,org):    
    traffic=Traffic.objects.get(pk=traffic_id)
    strategy=Strategy(start=traffic.start,end=traffic.end,deleted=False,organization=org)
    strategy.default_strategy()   
    strategy.landingpage=""     
    strategy.save()    

def get_media_by_levlel(request):
    if request.method == "POST":
        params = request.POST
    else:
        params = request.GET     
    results={}
    datalist=[]    
    id=params.get("id")
    level=int(params.get("lv",1))
    if level==1:
        objs=Media.objects.filter(deleted=False)
    elif level==2:
        media=Media.objects.get(pk=id)
        objs=media.position_set.filter(deleted=False)
    elif level==3:
        position=Position.objects.get(pk=id)
        objs=position.traffic_set.filter(deleted=False,active=True,TRAFFIC__allow_shared=True)          
    for obj in objs:
        data={}
        data["id"]=obj.id
        data["name"]=obj.name
        data["lv"]=level+1
        datalist.append(data)
    results["data"]=datalist
    return JsonResponse(results)

@login_required_ajax
def get_areas_by_level(request):
    if request.method == "POST":
        params = request.POST
    else:
        params = request.GET 
    id=params.get("id")
    code=params.get("code")    
    level=int(params.get("lv",1))
    if level==1:        #country
        areas=Area.objects.filter(code__endswith="000000")
    elif level==2:      #province
        str=code[0:4]
        areas=Area.objects.filter(code__startswith=str,code__endswith="0000").exclude(id=id)                
    elif level==3:      #city
        str=code[0:6]
        areas=Area.objects.filter(code__startswith=str,code__endswith="00").exclude(id=id)
    result={}
    datalist=[]
    for area in areas:
        data={}
        data["id"]=area.id
        data["name"]=area.name
        data["code"]=area.code
        data["lv"]=level+1
        datalist.append(data)
    result["data"]=datalist
    return JsonResponse(result)

# def get_material_size(request):
#     try :
#         org=request.user.account.get_organization()
#         size_lst=None
#         if org.type ==OrgType.PLATFORM and request.user.account.is_admin():
#             size_lst  = Material.objects.filter(deleted=False).values_list("width","height").order_by("width","height").distinct()
#         else :
#             size_lst = Material.objects.filter(organization__in= request.user.account.organization.all(),deleted=False).values_list("width","height").order_by("width","height").distinct()
#         data_arr =[]
#         for s in size_lst :
#             tmp = {}
#             tmp["width"]=s[0]
#             tmp["height"]=s[1]
#             data_arr.append(tmp)
#         return JsonResponse({"data":data_arr})
#     except Exception,e:
#         traceback.print_exc()
#         return JsonResponseBadrequest({"message":str(e)})

def get_position(sid):    
    resourceprices=ResourcePrice.objects.filter(strategy_id=sid,resource__deleted=False)
    check={}
    datas=[]
    for resourceprice in resourceprices:        
        position=resourceprice.resource.traffic.position
        if position.deleted==False and not check.get(position.id):
            check[position.id]=1
            data={}
            data["id"]=position.id
            data["name"]=position.name
            data["type"]=position.media.type
            datas.append(data)         
    return datas


# 平台策略花费
# CPM类型的广告位=策略在该广告位pv/1000 * CPM价格
# CPD类型广告位=策略在该广告位pv/广告位总pv * CPD价格

def get_strategy_dailyreport(pid,type,role,sid,start,end):
    start = datetime.datetime.strptime(start,"%Y-%m-%d").date()
    end = datetime.datetime.strptime(end,"%Y-%m-%d").date()
    datalist=[]
    if pid>0:
        objs=DailyStrategyPositionReport.objects.filter(strategy__id=sid,position__id=pid,date__range=(start, end)).order_by("date")\
        .values_list("date","pv","uv","click","cost")
    else:
        if not type:
            objs=DailyStrategyReport.objects.filter(strategy__id=sid,date__range=(start, end)).order_by("date")\
        .values_list("date","pv","uv","click","cost")
        else:
            type=int(type)
            objs=DailyStrategyMediaTypeReport.objects.filter(strategy__id=sid,date__range=(start, end),type=type).order_by("date")\
            .values_list("date","pv","uv","click","cost")
    dateArr = date_range_array(start,end)
    strategy_data_by_date ={}
    for pd in objs :
        d,pv,uv,click,cost=pd
        strategy_data_by_date[d]=(pv,uv,click,cost) 
    for d in dateArr:
        data={}
        pv,uv,click,cost = strategy_data_by_date.get(d,(0,0,0,0))
        data["click"]=click
        data["pv"]=pv
        data["uv"]=uv        
        data["ctr"]=0
        if pv !=0:
            data["ctr"]=floatformat(click / float(pv),arg=-5)
        data["date"] = d.strftime("%Y-%m-%d")        
        if role==2:
            data["cost"]=floatformat(cost,arg=-2)
            data["sale_income"]=floatformat(get_cost_by_strategy(d,sid,pid,type),arg=-2)   
            datalist.append(data)
            continue        
         
        data["cost"]=0
        if pid > 0:
            position_report=DailyPositionReport.objects.filter(position_id=pid,date=d)
            if position_report:
                position_pv=position_report[0].pv
                traffics=Traffic.objects.filter(position_id=pid,deleted=False,start__lte=d,end__gte=d)
                if traffics:
                    traffic=traffics[0]
                    bid_price=traffic.bid_price
                    if traffic.bid_type==0:
                        if position_pv:
                            data["cost"]=floatformat(pv*bid_price/float(position_pv),arg=-2)
                    else:
                        data["cost"]=floatformat(pv*bid_price/float(1000))
        else:
            kwargs={}
            if type:
                kwargs["resource__traffic__position__media__type"]=type
            resource_prices=ResourcePrice.objects.select_related("resource__traffic","resource__traffic__position").filter(strategy_id=sid,resource__deleted=False,resource__traffic__start__lte=d,resource__traffic__end__gte=d,**kwargs)
            check={}
            for resource_price in resource_prices:
                traffic = resource_price.resource.traffic
                position=traffic.position
                position_report=DailyStrategyPositionReport.objects.filter(position_id=position.id,strategy_id=sid,date=d)
                position_strategy_pv=0
                if position_report:
                    position_strategy_pv=position_report[0].pv
                bid_price=traffic.bid_price
                if traffic.bid_type==0:
                    position_report=DailyPositionReport.objects.filter(position_id=position.id,date=d)
                    if position_report:
                        position_pv=position_report[0].pv
                        if position_pv:
                            data["cost"]+=position_strategy_pv*bid_price/float(position_pv)
                else:
                    data["cost"]+=position_strategy_pv*bid_price/float(1000)
                         
            data["cost"]=floatformat(float(data["cost"]),arg=-2)    
        datalist.append(data)
    return datalist

def get_strategy_todayreport(id):
    result={}
    ids=[]    
    ids.append(id)
    statics_data=get_strategy_report(ids)
    if statics_data:
        result["cost"]=statics_data["strategyCosts"][0]["today"]
        result["click"]=statics_data["strategyClicks"][0]["today"]
        result["pv"]=statics_data["strategyImpressions"][0]["today"]
        result["ctr"]=result["click"]/float(result["impression"])
    return result

#媒体定向
@login_required_ajax
def get_resources(request):
    params = json.loads(request.body)
    search_text = params.get("search_text", "").strip()  # 模糊搜索
    start = params.get("start")
    end = params.get("end")
    order_by = params.get("orderBy", "-id")
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))
    
    account=request.user.account
    org=account.get_organization()    
   
    results={}   
    
    args = []  
    kwargs = {}  
    order = []  
    if start and end :
        args.append(Q(start__range=(start,end)) | Q(end__range=(start,end))|Q(start__lte=start,end__gte=end)|Q(start__gte=start,end__lte=end))  
    
    if search_text:
        args.append(Q(traffic__position__name__icontains=search_text) |                         
                         Q(traffic__position__media__name__icontains=search_text))
    if order_by:
        order.append(order_by)
    kwargs["end__gte"]=today()       
    args.append(Q(allow_shared=True)|Q(RESOURCE__organization=org))
    kwargs["deleted"]=False
    kwargs["traffic__active"]=True       
    list=Resource.objects.filter(*args,**kwargs).order_by("-id").distinct()
    paginator = Paginator(list, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)   
    datalist=[]        
    for obj in pageObj:
        
        data={}
        traffic=obj.traffic        
        position=traffic.position
        media=position.media
        qset=obj.RESOURCE.all()
        if qset.exists():
            allocation=qset[0]
            data["org"]=allocation.organization.name
        
        data["id"]=obj.id
        data["name"]=position.name
        data["width"]=position.width
        data["height"]=position.height
        data["type"]=get_tag_name(position.types.all())
        data["max"]=position.max
        data["media"]=media.name
        data["media_type"]=media.type        
        data["price"]=obj.floor
        data["start"]=obj.start
        data["end"]=obj.end
        data["hours"] = get_Field_list(obj.resourcehour_set.all(),"hour")
        data["areas"] = get_resource_area_name(obj)
        
        datalist.append(data)  
        
    results["bodyData"]=datalist   
    results["pageNo"] = pageNo
    results["pageSize"] = pageSize
    results["totalCount"] = paginator.count
    return JsonResponse(results)    

def strategy_to_json(objs,state):
    
    #cost/click/impression     
    total_cost={}
   # today_cost={}
    total_impression={}
    #today_impression={}
    total_click={}
    #today_click={}    
    ids=[]
    for obj in objs:        
        ids.append(obj.id)             
    statics_data=get_strategy_report(ids)
    if statics_data:
        costs=statics_data["strategyCosts"]
        impressions=statics_data["strategyImpressions"]
        clicks=statics_data["strategyClicks"] 
        i=0       
        while i <len(costs):
            id = costs[i]["id"]
            total = float(costs[i]["total_in"])+float(costs[i]["total_out"])+float(costs[i]["total_ally"])
     #       today = costs[i]["today"]
            total_cost[id] = total
      #      today_cost[id] = today
            total = clicks[i]["total"]
       #     today = clicks[i]["today"]
            total_click[id] = total
        #    today_click[id] = today
            total = int(impressions[i]["total_in"])+int( impressions[i]["total_out"])+int(impressions[i]["total_ally"])
         #   today = impressions[i]["today"]
            total_impression[id] = total
          #  today_impression[id] = today 
            i+=1 
    #strategy 
    data_list=[]
    for obj in objs:          
        data={}
        id=obj.id
        data["id"]=id
        data["name"]=obj.name
        data["start"]=obj.start
        data["end"]=obj.end    
        data["hours"]=get_hours(obj)
        data["areas"]=get_areas(id)
        data["words"]=get_words(id)
        data["cost"]=0
        data["click"]=0
        data["impression"]=0
        if total_cost:
            data["cost"]=floatformat(total_cost[id],arg=-2)  
        if total_click:
            data["click"]=total_click[id]             
        if total_impression:
            data["impression"]=total_impression[id]
        data["state"]=get_state(obj.start,obj.end,state)
        data_list.append(data)
    
    return data_list

def get_state(start,end,state):
    if state==-1:
        startTime = datetime.datetime(start.year,start.month,start.day)
        endTime = datetime.datetime(end.year,end.month,end.day)
        now=datetime.datetime.now()
        nowTime=datetime.datetime(now.year,now.month,now.day)
        if nowTime<startTime:
            status="未开始"
        elif nowTime>endTime:
            status="已结束"
        else:
            status="投放中"
    elif state==0:
        status="未开始"
    elif state==1:
        status="投放中"
    elif state==2:
        status="已结束"   
    return status   

def get_hours(strategy):
    hours=[]
    objs=strategy.hour_set.all()
    for obj in objs:
        hours.append(obj.hour)
    return hours

def get_areas(sid):
    datalist=[]
    objs=StrategyArea.objects.filter(strategy_id=sid)
    for obj in objs:
        data={}
        area=obj.area
        data["id"]=area.id
        data["name"]=area.name
        datalist.append(data)
    return datalist

# def get_areas(strategy,tag):
#     datas=[]
#     objs=strategy.strategyarea_set.all()
#     areasdata={}
#     for obj in objs:
#         data={}
#         area=obj.area     
#         data["id"]=area.id   
#         data["name"]=area.name
#         data["code"]=area.code
#         data["tag"]=1
#         datas.append(data)
#         if tag:
#             code=area.code      
#             country=code[0:4]
#             province=code[0:6]      
#             if code.endswith("000000"):#country               
#                 areasdata[country]=country
#             else:               
#                 if areasdata.get(country)==None:
#                     areasdata[country]=country
#                     areas=Area.objects.filter(code__startswith=country,code__endswith="000000")
#                     area=areas[0]
#                     data={}
#                     data["id"]=area.id
#                     data["name"]=area.name
#                     data["code"]=area.code
#                     data["tag"]=0
#                     datas.append(data)                    
#                 if not code.endswith("0000"):#
#                     if areasdata.get(province)==None:
#                         areasdata[province]=province
#                         areas=Area.objects.filter(code__startswith=province,code__endswith="0000")
#                         area=areas[0]
#                         data={}
#                         data["id"]=area.id
#                         data["name"]=area.name
#                         data["code"]=area.code
#                         data["tag"]=0
#                         datas.append(data)                 
#     return datas

def get_material_weights(strategy):
    datas=[]
    objs=strategy.materialweight_set.all()
    for obj in objs:
        data={}
        material=obj.material
        data["mid"]=material.id
        data["name"]=material.name
        data["weight"]=obj.weight
        data["group"]=obj.group
        datas.append(data)
    return datas        
        
def get_resource_prices(strategy):
    datas=[]
    objs=strategy.resourceprice_set.all()
    for obj in objs:
        data={}
        resource=obj.resource
        data["rid"]=resource.id
        data["name"]=resource.name
        data["price"]=obj.price
        datas.append(data)
    return datas     
    

@login_required_ajax
def get_strategy(request):
    try:
        if request.method == "POST":
            params = request.POST
        else:
            params = request.GET
        sid=int(params.get("id"))
        org=request.user.account.get_organization()
        result={}
        obj=Strategy.objects.get(pk=sid)
        result["name"]=obj.name
        result["start"]=obj.start
        result["end"]=obj.end
        result["frequency"]=obj.frequency
        result["landingPage"]=obj.landingpage
        result["dailyAmountIn"]=obj.daily_amount_in
        result["dailyAmountOut"]=obj.daily_amount_out
        result["dailyAmountAlly"]=obj.daily_amount_ally
        result["totalAmountIn"]=obj.total_amount_in
        result["totalAmountOut"]=obj.total_amount_out
        result["totalAmountAlly"]=obj.total_amount_ally
        result["dailyBudgetIn"]=obj.daily_budget_in
        result["dailyBudgetOut"]=obj.daily_budget_out
        result["dailyBudgetAlly"]=obj.daily_budget_ally
        result["totalBudgetIn"]=obj.total_budget_in
        result["totalBudgetOut"]=obj.total_budget_out
        result["totalBudgetAlly"]=obj.total_budget_ally
        result["consumeTypeIn"]=obj.consume_type_in
        result["consumeTypeOut"]=obj.consume_type_out
        result["consumeTypeAlly"]=obj.consume_type_ally
        algorithm=obj.algorithm
        if algorithm:
            result["alg"]={"id":obj.algorithm_id,"name":algorithm.name,"parameters":obj.parameters,"xml_format":algorithm.xml_format}
        result["hours"]=get_hours(obj)
        result["areas"]=get_areas(sid)
        result["words"]=get_words(sid)
        result["group"]=get_group_material(sid,org)
        data=get_strategy_traffic(obj)
        result["resource"]=data["data"]
        result["price"]= data["price"]
    except Exception,e:
        return JsonResponseBadrequest({'message':str(e)})    
    return JsonResponse(result)
   
def get_strategy_traffic(strategy):
    result={}
    datalist=[]
    objs=strategy.resourceprice_set.all()
    result["price"]=0
    tag=True    
    for obj in objs:
        resource=obj.resource        
        position=resource.traffic.position        
        data={}
        data["resource_id"]=resource.id
        data["position_name"]=position.name
        data["width"]=position.width
        data["height"]=position.height
        data["max"]=position.max
        data["type"]=get_tag_name(position.types.all())
        data["floor"]=resource.floor
        data["start"]=resource.start
        data["end"]=resource.end
        data["media_name"]=position.media.name
        data["hours"] = get_Field_list(resource.resourcehour_set.all(),"hour")
        data["areas"] = get_resource_area_name(resource)
        datalist.append(data)
        if tag and resource.allow_shared:
            if not resource.RESOURCE.all().exists():
                result["price"]= Decimal(str(obj.price))-Decimal(str(resource.floor))
                tag=False
                
    result["data"]=datalist
#     rps=ResourcePrice.objects.filter(strategy=strategy,resource__allow_shared=True,resource__deleted=False)
#     if rps:
#         result["price"]= rps[0].price-rps[0].resource.floor
#     else:
#         result["price"]=0 
    return result 


def get_strategy_price(strategy):
    price=0
    objs=strategy.resourceprice_set.filter(resource__allow_shared=True,resource__deleted=False)
    for obj in objs:
        resource=obj.resource
        if not resource.RESOURCE.all().exists():
            price= obj.price-resource.floor
            break
    return price
            
        
    


def get_Field_list(objs,field):
    data=[]
    for obj in objs:
        data.append(getattr(obj,field))
    return data

def get_resource_area_name(resource):
    data=[]
    objs=resource.resourcearea_set.all()
    for obj in objs:
        data.append(obj.area.name)
    return data
    

def get_default_resource_strategy(rid):
    rp=ResourcePrice.objects.get(resource_id=rid,strategy__priority=-5)
    return rp.strategy

def get_default_traffic_strategy(params):
    rid=params.get("rid")
    tid=params.get("tid")
    if  rid:
        rp=ResourcePrice.objects.get(resource_id=int(rid),strategy__priority=-10)
    else:        
        dafault_resource = Resource.objects.get(traffic_id=int(tid),is_default=True) 
        rp = ResourcePrice.objects.get(resource=dafault_resource,strategy__priority=-10)       
    return rp.strategy    

    
       
def build_resources_price(resource_ids,bid_price,type):
    result=[]
    for id in resource_ids:
        data={}
        if type==0:
            price=0
        else:
            resource=Resource.objects.get(pk=int(id))
            if resource.RESOURCE.all().exists():
                price=0
            else:
                price=resource.floor+bid_price
        data["resource_id"]=id
        data["price"]=price     
        result.append(data)       
    return result       


############################关键字HotWord###################

def get_key_words(request):
    if request.method == "POST":
        params = request.POST
    else:
        params = request.GET 
    id=params.get("id")  
    if not id:
        objs=HotWord.objects.filter(level=1)
    else:
        id=int(id)
        objs=HotWord.objects.filter(parent_id=id)        
    result={}
    datalist=[]
    for obj in objs:
        data={}
        data["id"]=obj.id
        data["name"]=obj.name        
        data["lv"]=obj.level
        datalist.append(data)
    result["data"]=datalist
    return JsonResponse(result)
        

def get_areas_tree(request):
    result={}
    datalist=[]
    
    
    data={}
    country_id=Area.objects.get(name="中国").id
    data["id"]=country_id
    data["pId"]=0
    data["name"]="中国"
    data["areacode"]="1156000000"
    datalist.append(data)
    
    provinces=Area.objects.filter(code__startswith="1156",code__endswith="0000").exclude(id=country_id)
    for province in provinces:
        data={}
        data["id"]=province.id
        data["pId"]=country_id
        data["name"]=province.name
        data["areacode"]=province.code
        province_code=province.code[0:6]
        datalist.append(data)
        cities=Area.objects.filter(code__startswith=province_code).exclude(id=province.id)
        for city in cities:
            data={}
            data["id"]=city.id
            data["pId"]=province.id
            data["name"]=city.name
            data["areacode"]=city.code
            datalist.append(data)    
    result["data"]=datalist
    return JsonResponse(result)


def get_hotwords_tree(request):
    result={}
    datalist=[]
    objs=HotWord.objects.all()
    for obj in objs:
        data={}
        data["id"]=obj.id
        data["name"]=obj.name
        data["pId"]=0        
        data["active"]=is_word_active(obj.last_update)
        if obj.parent:
            data["pId"]=obj.parent.id
        datalist.append(data)
    result["data"]=datalist
    return JsonResponse(result)

def get_words(sid):
    datalist=[]
    objs=StrategyWord.objects.filter(strategy_id=sid)
    for obj in objs:
        data={}
        hotword=obj.hotword
        data["id"]=hotword.id
        name=str(obj.name.encode("utf-8")).replace("&", "-")
        data["name"]=name
        datalist.append(data)
    return datalist
    

def is_word_active(date):
    tag=0
    now=datetime.datetime.now()
    today=datetime.datetime(now.year,now.month,now.day)
    word_date=datetime.datetime(date.year,date.month,date.day)
    if (today-word_date).days <= 30:
        tag=1
    return tag    

def get_resource_area(resource):
    datalist=[]
    objs=resource.resourcearea_set.all()
    for obj in objs:
        data={}
        area=obj.area
        data["id"]=area.id
        data["name"]=area.name
        datalist.append(data)
    return datalist

def get_valid_resources(request):
    result={}
    datalist=[]
    try:
        params = json.loads(request.body)
        traffic_id=params.get("traffic_id")
        resource_id=params.get("resource_id")
        account=request.user.account
        org=account.get_organization()
        args = []
        kwargs = {} 
        if traffic_id!=None and traffic_id!="":
            traffic_id=int(traffic_id)
            traffic=Traffic.objects.get(pk=traffic_id)
            result["start"]=traffic.start
            result["end"]=traffic.end                       
            kwargs["end__gte"]=today()
            args.append(Q(traffic_id=traffic_id))
            args.append(Q(allow_shared=True)|Q(RESOURCE__organization=org))
            kwargs["deleted"]=False
            resources=Resource.objects.filter(*args,**kwargs).order_by("-id").distinct()
        else:
            resource_id=int(resource_id)        
            resources=Resource.objects.filter(id=resource_id)            
            traffic=resources[0].traffic            
        position=traffic.position
        position_name=position.name
        width=position.width
        height=position.height
        max=position.max
        tag_name=get_tag_name(position.types.all())
        media_name=position.media.name
        for resource in resources:
            data={}
            data["resource_id"]=resource.id
            data["position_name"]=position_name
            data["width"]=width
            data["height"]=height
            data["max"]=max
            data["type"]=tag_name
            data["floor"]=resource.floor
            data["start"]=resource.start
            data["end"]=resource.end
            data["media_name"]=media_name
            data["hours"] = get_Field_list(resource.resourcehour_set.all(),"hour")
            data["areas"] = get_resource_area(resource)
            datalist.append(data)
        result["resource"]=datalist        
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({'message':str(e)})
    return JsonResponse(result)    
    

